import { createSlice, current, PayloadAction } from "@reduxjs/toolkit";
import { Song } from "../domain/Song";
import { SongListVo } from "../domain/SongList";

let currentSongInfo: Song = {
  id: -1,
  title: "Linkin Park - In The End",
  author: "unknown",
  genre: "unknown",
  album: "unknown",
  description: "no description...",
  duration: 600,
  thumbnail: "",
  mp3: "",
  belongTo: -1,
};
let allSongList: SongListVo[] = [];

let allSongFileList: Song[] = [];

type PlayModeType = "loop" | "iterate" | "shuffle";

let playMode: PlayModeType = "iterate" as PlayModeType;

let playHistory: Song["id"][] = [];

export const songSlice = createSlice({
  name: "song",
  initialState: {
    currentSongInfo,
    allSongList,
    allSongFileList,
    playMode,
    playHistory,
  },
  reducers: {
    goBack: (state, action: PayloadAction<null>) => {
      const newHist = [...state.playHistory].slice(
        0,
        state.playHistory.length - 1 < 1 ? 1 : state.playHistory.length - 1
      );
      // console.log(newHist, "goBack");
      return { ...state, playHistory: newHist };
    },
    updatePlayHistory: (state, action: PayloadAction<Song>) => {
      return {
        ...state,
        playHistory: [...state.playHistory, action.payload.id],
      };
    },
    setCurrentSongInfo: (state, action: PayloadAction<Song>) => {
      return {
        ...state,
        currentSongInfo: action.payload,
      };
    },
    updateAllSongList: (state, action: PayloadAction<SongListVo[]>) => {
      // state.allSongList = action.payload;
      return { ...state, allSongList: action.payload };
    },
    updateAllSongFileList: (state, action: PayloadAction<Song[]>) => {
      // state.allSongFileList = action.payload;
      // return state;
      return { ...state, allSongFileList: action.payload };
    },
    // action: PayloadAction<PlayModeType>
    updatePlayMode: (state, action: PayloadAction<null>) => {
      const newMode =
        state.playMode === "iterate"
          ? "loop"
          : state.playMode === "loop"
          ? "shuffle"
          : "iterate";
      return { ...state, playMode: newMode };
    },
  },
});

export const songReducer = songSlice.reducer;

export const {
  updateAllSongList,
  updateAllSongFileList,
  setCurrentSongInfo,
  updatePlayMode,
  goBack,
  updatePlayHistory,
} = songSlice.actions;
